import appConfig from '@/utils/app-config'

let url=''
const baseWsUrl = appConfig.idcUrlConfig.wsUrl ;
let websocket = null
let lockReconnect = false;//避免重复连接
let tt;//定时器
let onmessageFun;
export default {
  //提供外部函数 初始化websocket
  createWebSocket(userId,fun){
    url=baseWsUrl+userId
    onmessageFun=fun
    create()
  }
}

function create() {
  try {
    //创建ws实例
    websocket = new WebSocket(url);
    init();
  } catch(e) {
    console.log('catch');
    reconnect();
  }
}
//回调函数初始化 处理消息函数onmessage外部传递进来
function init() {
  websocket.onclose = function () {
    console.log('链接关闭');
    reconnect(url);
  };
  websocket.onerror = function() {
    console.log('发生异常了');
    reconnect(url);
  };
  websocket.onopen = function () {
    //心跳检测重置
    heartCheck.start();
  };
  websocket.onmessage = function (event) {
    //拿到任何消息都说明当前连接是正常的
    //console.log('接收到消息'+event.data);
    onmessageFun(event)
    heartCheck.start();
  }
}
//重连
function reconnect() {
  if(lockReconnect) {
    return;
  }
  lockReconnect = true;
  //没连接上会一直重连，设置延迟避免请求过多
  tt && clearTimeout(tt);
  tt = setTimeout(function () {
    create();
    lockReconnect = false;
  }, 4000);
}
//心跳检测
let heartCheck = {
  timeout: 10000,//心跳间隔
  timeoutObj: null,
  serverTimeoutObj: null,
  start: function(){
    // console.log('ping...');
    let self = this;
    const msg={data:"ping",type:0}
    this.timeoutObj && clearTimeout(this.timeoutObj);
    this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
    this.timeoutObj = setTimeout(function(){
      //这里发送一个心跳，后端收到后，返回一个心跳消息，
      //console.log(JSON.stringify(msg));
      websocket.send(JSON.stringify(msg));
      self.serverTimeoutObj = setTimeout(function() {
        //console.log(111);
        //console.log(websocket);
        websocket.close();
        // createWebSocket();
      }, self.timeout);

    }, this.timeout)
  }


}
